<template>
    <div class="container">
        <div class="createMp" v-if="mpStatus === 0">
            <div class="choose">
                <div v-if="componyStatus === 0" class="createMp-tip">
                    提示：授权小程序前，请先进行<span @click="companyAuthHandler" class="pointer">企业认证</span>
                </div>
                <img src="@/assets/imgs/sys/mp-logo.png" alt="" />
                <span>已有微信小程序</span>
                <span class="auth pointer" @click="grantHandler">立即授权</span>
            </div>
            <div class="choose">
                <img src="@/assets/imgs/sys/mp-logo.png" alt="" />
                <span>没有微信小程序</span>
                <span class="auth pointer" @click="registerHandler">立即注册</span>
            </div>
        </div>
        <div class="infoWrap" v-if="mpStatus === 1">
            <div class="tips">
                <div class="tip-item" @click="guideHandler(1)">
                    <img class="tip-icon" src="@/assets/imgs/tip.png" />
                    <span>怎么修改小程序基本信息？</span>
                </div>
                <div class="tip-item" @click="guideHandler(2)">
                    <img class="tip-icon" src="@/assets/imgs/tip.png" />
                    <span>怎么解除授权小程序？</span>
                </div>
                <div class="tip-item" @click="guideHandler(3)">
                    <img class="tip-icon" src="@/assets/imgs/tip.png" />
                    <span>怎么设置小程序登录邮箱和密码？</span>
                </div>
            </div>
            <div class="title"><span></span>基本信息</div>
            <div class="info">
                <span class="label">APPID（小程序ID）：</span>
                <div>{{ Data.appid }}</div>
                <span class="copybtn" @click="copyHandler">复制</span>
            </div>
            <div class="info">
                <span class="label">原始ID：</span>
                <div>{{ showFiledValueHandler(Data.originId) }}</div>
            </div>
            <div class="info">
                <span class="label">小程序名称：</span>
                <div>{{ showFiledValueHandler(Data.name) }}</div>
            </div>
            <div class="info">
                <span class="logo label">小程序头像：</span>
                <div>
                    <el-avatar :size="64" :src="Data.logo"> </el-avatar>
                </div>
            </div>
            <div class="info">
                <span class="label">小程序介绍：</span>
                <div class="group">
                    <span>{{ showFiledValueHandler(Data.signature) }}</span>
                    <span class="copybtn" @click="guideHandler(1)" v-if="!Data.signature">去完善</span>
                </div>
            </div>
            <div class="info">
                <span class="label">服务类目：</span>
                <div class="group" v-if="Data.categories.length === 0">
                    <span>-</span>
                    <span class="copybtn" @click="guideHandler(1)">去完善</span>
                </div>
                <div v-else>
                    <div v-for="(item, idx) in Data.categories" :key="item.firstName + idx">
                        {{ item.firstName }}/{{ item.secondName }}
                    </div>
                </div>
            </div>
            <div class="info">
                <span class="label">主体信息：</span>
                <div>{{ Data.businessName }}</div>
            </div>
            <div class="info">
                <span class="logo label">小程序码：</span>
                <div class="group">
                    <el-avatar :size="64" :src="Data.miniAppUrl"> </el-avatar>
                    <span class="copybtn" v-if="Data.miniAppUrl" @click="downloadImgHandler(Data.miniAppUrl, Data.name)"
                        >下载</span
                    >
                </div>
            </div>
            <div class="title"><span></span>版本信息</div>
            <div class="infoWrap">
                <div class="info">
                    <span class="label">当前版本：</span>
                    <div class="current">
                        <span class="mr10" v-if="VSInfo.currentVersion">{{ VSInfo.currentVersion }}</span>
                        <span class="nopub" v-if="!VSInfo.currentVersion">尚未发布</span>
                        <div class="exam">
                            <span @click="commitHandler" v-if="VSInfo.canCommit === 1">提交审核</span>
                            <el-tooltip
                                effect="dark"
                                content="小程序基本信息尚未完善，无法提交审核"
                                placement="top"
                                v-if="VSInfo.canCommit === 2">
                                <span class="disabled">提交审核</span>
                            </el-tooltip>
                        </div>
                        <div class="exam" v-if="VSInfo.canUpdate === 1">
                            <span @click="commitHandler">升级</span>
                        </div>
                    </div>
                </div>
                <div class="info">
                    <span class="label">更新时间：</span>
                    <span>{{ showFiledValueHandler(VSInfo.updateTime) }}</span>
                </div>
                <div class="info">
                    <span class="label">更新状态：</span>
                    <div class="value">
                        <div class="update-status">
                            <span class="mr10">{{ showFiledValueHandler(VSInfo.commitStatusDesc) }}</span>
                            <div class="exam mr10" v-if="VSInfo.commitStatus === 3">
                                <span @click="commitHandler">重新提交审核</span>
                            </div>
                            <div class="exam" v-if="VSInfo.canCancel === 1">
                                <span @click="cancelCommitHandler">取消升级</span>
                            </div>
                        </div>
                        <div class="fail-reason" v-if="VSInfo.commitStatus === 3">
                            <span>失败原因：</span>
                            <span class="mr10">{{ VSInfo.rejectReason }}</span>
                            <span class="exam" v-if="VSInfo.code === 2005012" @click="guideHandler(4)"
                                >开通接口权限</span
                            >
                            <span class="exam" v-if="VSInfo.code === 2005013" @click="guideHandler(5)"
                                >配置服务器域名</span
                            >
                        </div>
                    </div>
                </div>
                <div class="info">
                    <span class="label">最新版本：</span>
                    <span class="mr10">{{ showFiledValueHandler(VSInfo.lastPublishVersion) }}</span>
                    <el-popover
                        placement="bottom"
                        :title="`${VSInfo.lastPublishVersion}版本说明`"
                        :width="200"
                        trigger="click"
                        :content="VSInfo.lastPublishVersionDesc">
                        <template #reference>
                            <span class="exam">版本说明</span>
                        </template>
                    </el-popover>
                </div>
                <div class="info">
                    <span class="label">体验二维码：</span>
                    <div class="exam">
                        <div>
                            <el-tooltip
                                effect="dark"
                                content="暂无小程序版本，无法生成小程序二维码"
                                placement="top"
                                v-if="experienceUrlFlag">
                                <span>生成体验二维码</span>
                            </el-tooltip>
                            <span v-else @click="showQrHandler">生成体验二维码</span>
                        </div>
                        <span class="nopub mt10 f11">微信扫描体验二维码体验最新小程序</span>
                    </div>
                </div>
            </div>
            <div class="title">
                <span></span>支付信息
                <PayAppSetting></PayAppSetting>
            </div>
            <div class="payWrapper" v-if="paymentList.length > 0">
                <div class="payItem" v-for="item in paymentList" :key="item.id">
                    <div :class="['baofu', item.channelCode === 'WECHAT' && 'wechat']">
                        <img v-if="item.channelCode === 'BAOFU'" src="@/assets/imgs/sys/baofu-logo.png" alt="" />
                        <img v-if="item.channelCode === 'WECHAT'" src="@/assets/imgs/sys/wechat-logo.png" alt="" />
                        <span>{{ item.channelName }}</span>
                        <div :class="[item.openStatus === 1 && 'complete']">
                            {{ item.openStatus === 1 ? '已配置' : '未配置' }}
                        </div>
                    </div>
                    <div class="btnWrapper">
                        <el-button class="warning" type="primary" @click="jumpHandler(item.channelCode)">
                            {{ item.openStatus === 1 ? '查看配置' : '去配置' }}
                        </el-button>
                        <div
                            :class="Data.defaultPayCode === 'BAOFU' ? 'btn default' : 'btn'"
                            type="warning"
                            v-if="item.channelCode === 'BAOFU'"
                            plain
                            @click="paySetHandler(item.channelCode)">
                            {{ Data.defaultPayCode !== 'BAOFU' ? '设为默认支付渠道' : '默认支付渠道' }}
                        </div>
                        <div
                            :class="Data.defaultPayCode === 'WECHAT' ? 'btn default' : 'btn'"
                            v-if="item.channelCode === 'WECHAT'"
                            @click="paySetHandler(item.channelCode)">
                            {{ Data.defaultPayCode !== 'WECHAT' ? '设为默认支付渠道' : '默认支付渠道' }}
                        </div>
                    </div>
                </div>
            </div>
            <el-dialog v-model="guideShow" width="40%">
                <template #header>
                    <span v-if="guideType === 1">完善小程序基本信息</span>
                    <span v-if="guideType === 2">解除授权</span>
                    <span v-if="guideType === 4">开通接口权限</span>
                    <span v-if="guideType === 5">配置服务器域名</span>
                </template>
                <template #default>
                    <div v-if="guideType === 1">
                        <span class="title">你需要在微信公众平台完善小程序基本信息。</span>
                        <div class="cxt">
                            <p>1. 进入微信公众平台 - 点击左侧菜单栏 “设置” ；</p>
                            <p>2. 在 “基本设置” tab页面完善小程序基本信息。</p>
                            <img class="schematic_img" src="/imgs/baseinfo_update.png" />
                        </div>
                    </div>
                    <div v-if="guideType === 2">
                        <span class="title">由于微信公众平台规定，你需要在微信公众平台解除授权。</span>
                        <div class="cxt">
                            <p>1. 进入微信公众平台 - 点击左侧菜单栏 “设置” ；</p>
                            <p>2. 在 “第三方设置” tab页面解除授权。</p>
                            <img class="schematic_img" src="/imgs/mp_out.png" />
                        </div>
                    </div>
                    <div v-if="guideType === 4">
                        <span class="title">你需要在微信公众平台完善小程序基本信息。</span>
                        <div class="cxt">
                            <p>1. 进入微信公众平台 - 点击左侧菜单栏 “开发管理” ；</p>
                            <p>2. 在 “接口设置” tab页面开通所需接口权限。</p>
                            <img class="schematic_img" src="/imgs/auth_open.png" />
                        </div>
                    </div>
                    <div v-if="guideType === 5">
                        <span class="title">你需要在微信公众平台完善小程序基本信息。</span>
                        <div class="cxt">
                            <p>1. 进入微信公众平台 - 点击左侧菜单栏 “开发管理” ；</p>
                            <p>2. 在 “开发设置” tab页面服务器域名区域修改域名。</p>
                            <img class="schematic_img" src="/imgs/server_set.png" />
                        </div>
                    </div>
                </template>
                <template #footer>
                    <div style="flex: auto">
                        <el-button type="primary" @click="gotoMpHandler">前往微信公众平台</el-button>
                    </div>
                </template>
            </el-dialog>
            <el-dialog v-model="qrShow" width="30%">
                <template #header>
                    <span>小程序体验二维码</span>
                </template>
                <template #default>
                    <div class="qrdiv">
                        <img :src="experienceUrl" />
                    </div>
                </template>
                <template #footer>
                    <el-button type="primary" @click="downloadImgHandler(experienceUrl, Data.name)">下载</el-button>
                </template>
            </el-dialog>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, inject } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/request';
import { ElMessage } from 'element-plus';
import { isNotEmpty, downloadImgHandler } from '@/commons/utils';
import useClipboard from 'vue-clipboard3';
import storage from '@/commons/storage';
import PayAppSetting from './payAppSetting.vue';

const router = useRouter();
const confirm = inject('confirm');
let mpStatus = ref(-1);
let componyStatus = ref(0);
let Data = reactive({
    appid: '',
    businessName: '',
    categories: [],
    currentVersion: '',
    commitStatusDesc: '',
    defaultPayCode: ''
});
let VSInfo = reactive({});
const paymentList = reactive([]);
let guideShow = ref(false);
let guideType = ref(0);
let qrShow = ref(false);
let experienceUrl = ref('');
let experienceUrlFlag = ref(false);

/**
 * 获取信息
 */
onMounted(() => {
    queryAppInfo();
});

/**
 * 设为默认支付渠道
 * @param {*} code
 */
const paySetHandler = async code => {
    if (code === Data.defaultPayCode) return;
    if (code === 'BAOFU') {
        // 检查宝付通签约状态
        const { data } = await request('baofuRegInfo', { tenantId: storage.get('ZW-TENANT-ID') });
        if (!data.loginNo) {
            ElMessage({
                type: 'error',
                message: '宝付支付暂未开通成功，不可设为默认支付渠道'
            });
            return;
        }
        // appid 和 simId 绑定
        const result = await request('bindSimIdServ', { appId: Data.appid });
        if (![0, 4000003].includes(result.code)) {
            ElMessage({
                type: 'error',
                message: result.msg
            });
            return;
        }
    }
    const { data } = await request('paymentDefault', {
        defaultPayCode: code
    });
    ElMessage({
        type: 'success',
        message: '设置成功~',
        duration: 2000
    });
    // 先变再查
    Data.defaultPayCode = code;
    queryAppInfo();
};

const jumpHandler = code => {
    if (code === 'BAOFU') {
        router.push('/pay/account');
    } else {
        router.push('/pay/mp');
    }
};

/**
 * 提交审核、重新提交审核、升级
 * @param {*} type
 */
const commitHandler = async type => {
    try {
        if (await confirm(`你确定要提交审核吗？`, 'warning')) {
            await request('miniappRecommitServ');
            ElMessage.success('操作成功！');
            queryAppInfo();
        }
    } catch (e) {}
};

/**
 * 取消升级
 */
const cancelCommitHandler = async () => {
    try {
        if (await confirm(`你确定要取消升级吗？`, 'warning')) {
            await request('miniappCancelCommitServ');
            ElMessage.success('操作成功！');
            queryAppInfo();
        }
    } catch (e) {}
};

/**
 * 跳转注册页
 */
const registerHandler = () => {
    if (componyStatus.value !== 1) {
        ElMessage({
            type: 'warning',
            message: '请先完成企业认证!'
        });
        return;
    }
    router.push({ path: '/mp/info/register' });
};

/**
 * 查询小程序注册信息
 */
const queryAppInfo = () => {
    request('miniappInfoServ').then(res => {
        // 企业认证 1是 2 否
        if (res.data.isAuthBusiness === 1) {
            componyStatus.value = 1;
            mpStatus.value = 0;
        }
        // 小程序认证 1是 2否
        if (res.data.isRegMiniApp === 1) {
            mpStatus.value = 1;
            getPaymentList();
            Data = Object.assign(Data, res.data);
            VSInfo = Object.assign(VSInfo, res.data.versionInfo || {}, {
                categories: res.data.categories || []
            });
        }
        if (res.data.isRegMiniApp === 2) {
            mpStatus.value = 0;
        }
    });
};

/**
 * 获取支付信息列表
 */
const getPaymentList = async () => {
    const { data } = await request('paymentChannelList', {
        tenantId: storage.get('ZW-TENANT-ID'),
        payChannel: ''
    });
    if (data.list) {
        paymentList.length = 0;
        data.list.map(item => paymentList.push(item));
    }
};

/**
 * 去授权
 */
const grantHandler = () => {
    if (componyStatus.value !== 1) {
        ElMessage({
            type: 'warning',
            message: '请先完成企业认证!'
        });
        return;
    }
    const url = 'https://' + window.location.host + '/mp/redirect?type=mp';
    request('miniappAuthLinkServ', {
        callbackFrontUrl: url,
        authType: 2
    }).then(res => {
        const url = res.data.url;
        if (url) {
            window.location = url;
        }
    });
};

/**
 * 企业认证
 */
const companyAuthHandler = () => {
    router.push('/store/info');
};

/**
 * 企微文档
 * @param {*} type
 */
const guideHandler = type => {
    if (type === 3) {
        window.open('https://developers.weixin.qq.com/community/develop/doc/000c4c6ffb43f809859a0da4456001');
    } else {
        guideShow.value = true;
        guideType.value = type;
    }
};

/**
 * 去微信后台
 */
const gotoMpHandler = () => {
    window.open('https://mp.weixin.qq.com/');
};

/**
 * 显示二维码
 * @param {*} experienceUrl
 */
const showQrHandler = async () => {
    if (experienceUrlFlag.value) return;
    if (experienceUrl.value) {
        qrShow.value = true;
        return;
    }
    const { data } = await request('getExperienceServ');
    if (!data.experienceUrl) {
        experienceUrlFlag.value = true;
        return;
    }
    experienceUrl.value = data.experienceUrl;
    qrShow.value = true;
};

/**
 * 复制
 */
const copyHandler = async () => {
    const { toClipboard } = useClipboard();
    try {
        await toClipboard(Data.appid);
        ElMessage.success('复制成功');
    } catch (e) {}
};

/**
 * 显示字段内容
 * @param {*} value
 */
const showFiledValueHandler = value => {
    return isNotEmpty(value) ? value : '-';
};
</script>
<style lang="scss" src="./style.scss" scoped></style>
